package com.csw.springbootquartz.task.runstop;

import com.csw.springbootquartz.entity.SchedulerJobEntity;
import com.csw.springbootquartz.service.SchedulerJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;

@RestController
@RequestMapping("a")
public class SchedulerJobController {
    @Autowired
    private SchedulerJobService schedulerJobService;
    @Autowired
    private ControllerTask controllerTask;
    @Autowired
    private ControllerTask2 controllerTask2;


    /**
     * http://localhost:8080/a/b?id=111&cron=0/5%20*%20*%20*%20*%20?&running=on
     *
     * @param id
     * @param cron
     * @param running
     */
    @RequestMapping("b")
    public void startb(String id, String cron, String running) throws Exception {

        try {
            //        log.error("new cron :{}", cron);
            schedulerJobService.updateCronById(id, cron, running);
            SchedulerJobEntity schedulerJobEntity = schedulerJobService.findByid(id);
            String classPath = schedulerJobEntity.getClassPath();
            // 获取类的Class对象
            Class<?> clazz = Class.forName(classPath);

            // 创建类的实例对象, 不能获取autowire注入的
            // run.invoke(obj);
            //Object obj = clazz.newInstance();

            String className = classPath.substring(classPath.lastIndexOf(".") + 1);
            String firstZiMu = className.substring(0, 1).toLowerCase() + className.substring(1);
            // 获取方法对象
            Method run = clazz.getMethod("run", null);
            Method stopJob = clazz.getMethod("stopJob", null);

            ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
            if ("on".equals(running)) {
                run.invoke(applicationContext.getBean(firstZiMu));
            } else {
                stopJob.invoke(applicationContext.getBean(firstZiMu));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }



}
